﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubanApi.Models;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;

namespace DoubanApi.Helper
{
    internal class DoubanDataResolve
    {
        public MovieModel MovieResolve(string _xmldata)
        {
            MovieModel model = new MovieModel();

            XElement root = XElement.Parse(_xmldata);
            string defaultNamespace = root.GetDefaultNamespace().NamespaceName;
            string dbNamespace = root.GetNamespaceOfPrefix("db").NamespaceName;

            //model.Title = root.Element(XName.Get("title", defaultNamespace)).Value;

            model.ApiUrl = root.Element(XName.Get("id", defaultNamespace)).Value;

            model.Writer = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "writer")
                .ToList().ForEach((p) =>
                    {
                        model.Writer.Add(p.Value);
                    });

            model.Director = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "director")
                .ToList().ForEach((p) =>
                {
                    model.Director.Add(p.Value);
                });

            model.Cast = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "cast")
                .ToList().ForEach((p) =>
                {
                    model.Cast.Add(p.Value);
                });


            model.Movie_Type = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "movie_type")
                .ToList().ForEach((p) =>
                {
                    model.Movie_Type.Add(p.Value);
                });

            model.Country = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "country")
                .ToList().ForEach((p) =>
                {
                    model.Country.Add(p.Value);
                });

            model.Language = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "language")
                .ToList().ForEach((p) =>
                {
                    model.Language.Add(p.Value);
                });


            model.Pubdate = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "pubdate")
                .ToList().ForEach((p) =>
                    {
                        model.Pubdate.Add(p.Value);
                    });



            model.Movie_Duration = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "movie_duration")
                .ToList().ForEach((p) =>
                {
                    model.Movie_Duration.Add(p.Value);
                });


            model.Aka = new DoubanListCollection<string>();
            root.Elements(XName.Get("attribute", dbNamespace)).Where(p => p.Attribute("name").Value == "aka")
                .ToList().ForEach((p) =>
                {
                    model.Aka.Add(p.Value);
                });
            if (model.Aka.Count == 0)
            {
                model.Aka.Add(root.Element(XName.Get("title", defaultNamespace)).Value);
            }
            model.Summary = root.Element(XName.Get("summary", defaultNamespace)).Value;

            model.DoubanLink = root.Elements(XName.Get("link", defaultNamespace)).Where(p => p.Attribute("rel").Value == "alternate").First().Attribute("href").Value;

            string aImageUrl = root.Elements(XName.Get("link", defaultNamespace)).Where(p => p.Attribute("rel").Value == "image").First().Attribute("href").Value;
            model.ImageLink = aImageUrl.Replace("spic", "mpic");
            model.ImageLinkBig = aImageUrl.Replace("spic", "lpic");
            return model;
        }

        public string[] UserMovieFavoritesResolve(string _xmldata)
        {
            XElement root = XElement.Parse(_xmldata);
            string defaultNamespace = root.GetDefaultNamespace().NamespaceName;
            string dbNamespace = root.GetNamespaceOfPrefix("db").NamespaceName;

            string[] movieidlist = root.Descendants(XName.Get("link", defaultNamespace)).Where(p => p.Attribute("rel").Value == "http://www.douban.com/2007#subject").Select(p => p.Attribute("href").Value).ToArray();
            return movieidlist;
        }

        public void MoviePreviewResolve(string html, MovieModel model)
        {
            Regex regex = new Regex("<a class=\"trail_link\".*</a>");
            Match hrefmatch = regex.Match(html);
            if (hrefmatch != null && hrefmatch.Success)
            {
                string hrefstr = hrefmatch.Value;
                int subbegin = hrefstr.IndexOf("trailer/") + 8;
                int subend = hrefstr.IndexOf("/#content");
                string id = hrefstr.Substring(subbegin, subend - subbegin);
                model.Preview = new MoviePreviewModel() { Url = string.Format(StringConst.MoviePreviewUrl, id), Id = id };
            }
            else
            {
                model.Preview = new MoviePreviewModel();
            }
        }

        public void MoviePreviewImageResolve(string html, MovieModel model)
        {

            int begin = html.IndexOf("<ul class=\"pic-col5 clearfix\">", StringComparison.OrdinalIgnoreCase);
            if (begin > -1)
            {
                int end = html.IndexOf("</ul>", begin, StringComparison.OrdinalIgnoreCase);


                if (begin > -1 && end > -1)
                {
                    string value = html.Substring(begin, end - begin + 5);
                    XElement root = XElement.Parse(value);
                    model.PreviewImages = new DoubanListCollection<PreviewImageModel>();
                    foreach (var item in root.Descendants("a"))
                    {
                        string href = item.Attribute("href").Value;
                        if (href.EndsWith("/"))
                        {
                            href = href.Substring(0, href.Length - 1);
                        }

                        string id = href.Substring(href.LastIndexOf('/') + 1);

                        model.PreviewImages.Add(new PreviewImageModel()
                        {
                            BigImageUrl = string.Format(StringConst.PreviewImageBig, id),
                            SamillImageUrl = string.Format(StringConst.PreviewImageSmall, id)
                        });
                    }
                }
            }
            else
            {
                model.PreviewImages = new DoubanListCollection<PreviewImageModel>();
            }
        }

        public void MoviePreviewYoukuResolve(string html, MovieModel model)
        {
            int begin = html.IndexOf("<div class=\"btnprevue_large\">", StringComparison.OrdinalIgnoreCase);
            if (begin > -1)
            {
                int subbegin = html.IndexOf("id_",begin) + 3;
                int subend = html.IndexOf(".html", subbegin);
                string id = html.Substring(subbegin, subend - subbegin);
                model.Preview = new MoviePreviewModel() { Url=string.Format(StringConst.PreviewYoukuMovie,id), Id = id };
            }
            else
            {
                model.Preview = new MoviePreviewModel();
            }
        
         
        }

        public List<string> SearchResultResolve(string _xmldata)
        {
            List<string> aMovieApiAddress = new List<string>();
            XElement root = XElement.Parse(_xmldata);
            string defaultNamespace = root.GetDefaultNamespace().NamespaceName;
            string dbNamespace = root.GetNamespaceOfPrefix("db").NamespaceName;


            foreach (var aMovieEntry in root.Elements(XName.Get("entry", defaultNamespace)))
            {
                aMovieApiAddress.Add(aMovieEntry.Element(XName.Get("id", defaultNamespace)).Value);
            }


            return aMovieApiAddress;
        }
    }
}
